package tum0r.image;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 图片Gamma调整类，可调整图片亮度，当gammaValue<0时为调亮，大于1时为调暗
 * <p>
 * ClassName: Gamma
 * Author: tum0r
 * Time: 2020/4/11 11:53
 */
public class Gamma extends ImageBase {

    // 默认为调亮图片
    private double gammaValue = 0.454545;
    private static int[] gammaPixelsValue = null;

    public Gamma() {
        init();
    }

    public Gamma(double gammaValue) {
        this.gammaValue = gammaValue;
        init();
    }

    // 初始化颜色数字经过gamma调整后的值
    public void init() {
        if (gammaPixelsValue == null) {
            gammaPixelsValue = new int[256];
            for (int i = 0; i < gammaPixelsValue.length; i++) {
                gammaPixelsValue[i] = (int) (255 * Math.exp(Math.log(i / 255.0) * gammaValue));
            }
        }
    }

    /**
     * 处理图片，调整其亮度，使之变暗(gammaValue>1)或变亮(gammaValue<1)
     *
     * @param image 要调整亮度的图片BufferedImage对象
     * @return Gamma调整后图片BufferedImage对象
     */
    @Override
    public BufferedImage handle(BufferedImage image) {
        BufferedImage result = null;
        if (image != null) {
            int width = image.getWidth();
            int height = image.getHeight();
            result = new BufferedImage(width, height, image.getType());
            Color color;
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int ARGB = image.getRGB(x, y);
                    int alpha = (ARGB >> 24) & 0xff;
                    int red = (ARGB >> 16) & 0xff;
                    int green = (ARGB >> 8) & 0xff;
                    int blue = ARGB & 0xff;

                    color = new Color(gammaPixelsValue[red], gammaPixelsValue[green], gammaPixelsValue[blue], alpha);

                    result.setRGB(x, y, color.getRGB());
                }
            }
        }
        return result;
    }
}
